﻿using FastCloud.Base.Enum;
using FastORM.Applicaiton;
using FastORM.Entity;
using FastORM.Enum;
using FastUtil.Config;
using FastUtil.Convert;
using FastUtil.Extra;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace FastCloud.Base.Config
{
    public class TaskContext
    {
        public static async void Init()
        {
            DirectoryInfo PluginLogDir = new DirectoryInfo(CloudUtil.GetContentPath() + "/Logs/QuartzUtil");
            if (!PluginLogDir.Exists)
            {
                PluginLogDir.Create();
            }

            QuartzUtil.InitPlugin(AppConfigUtil.Configuration["Frame:SchedulerPlugin"]);
            IScheduler Scheduler = await QuartzUtil.GetScheduler();
            await QuartzUtil.CloseScheduler();
            CommonDao CD = new CommonDao(DataBaseClass.MySql, CloudUtil.GetBaseConnectString());
            DataTable dt = CD.FindViewList("select * from Frame_Task where TaskStatus=@TaskStatus", new List<ParamEntity>() { new ParamEntity() { ParamName = "TaskStatus", ParamValue = (int)Extend.TaskStatus.运行 } });
            foreach (DataRow item in dt.Rows)
            {

                int TaskType = ValueConvert.ConvertToInt32(item["TaskType"]);
                string TaskName = ValueConvert.ConvertToString(item["TaskName"]);
                string TaskTag = ValueConvert.ConvertToString(item["TaskTag"]);
                int TaskExecutePeriod = ValueConvert.ConvertToInt32(item["TaskExecutePeriod"]);
                int TaskExecuteUnit = ValueConvert.ConvertToInt32(item["TaskExecuteUnit"]);
                string CornExplain = ValueConvert.ConvertToString(item["CornExplain"]);
                JobDataMap jobData = new JobDataMap();
                jobData.Add("TaskName", TaskName);
                jobData.Add("TaskTag", TaskTag);
                IJobDetail job = JobBuilder.Create(Type.GetType(ValueConvert.ConvertToString(item["JobClassName"]))).SetJobData(jobData).Build();
                ITrigger trigger = null;
                if (TaskType == 100)
                {
                    trigger = QuartzUtil.GetCycleTrigger(TaskName, TaskTag, TaskExecutePeriod, TaskExecuteUnit);
                }
                else if (TaskType == 200)
                {
                    trigger = QuartzUtil.GetCornTrigger(TaskName, TaskTag, CornExplain);
                }
                await Scheduler.ScheduleJob(job, trigger);
            }
            await Scheduler.Start();
        }
    }
}
